import 'dart:async';
import 'dart:ui';
import 'package:eh_mobile/common/utils/index.dart';
import 'package:eh_mobile/common/utils/toast/bnw_toast.dart';
import 'package:eh_mobile/common/values/svg_image.dart';
import 'package:eh_mobile/pages/main/smart_home_info/widgets/light_card_item.dart';
import 'package:eh_mobile/pages/main/smart_home_info/widgets/temp_card_item.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import '../../homepage/model/home_device_model.dart';

// 灯光控制列表页面弹窗
typedef LightCardOverlayCallback = void Function(
    {bool? isEdit, bool? isRename, String? name});

class LightCardOverlay {
  final Offset offset;
  final Size size;
  final DeviceLListType deviceLListType;
  final HomeDeviceModelDevices lightCardModel;
  late OverlayEntry _overlayFloat;
  final LightCardOverlayCallback lightCardOverlayCallback;
  LightCardOverlay.show(
    BuildContext context, {
    required this.offset,
    required this.size,
    required this.deviceLListType,
    required this.lightCardModel,
    required this.lightCardOverlayCallback,
  }) {
    _overlayFloat = OverlayEntry(
      builder: (context) => MyDetailOverlay(
        offset: offset,
        size: size,
        deviceLListType: deviceLListType,
        lightCardModel: lightCardModel,
        lightCardOverlayCallback: (
            {bool? isEdit, bool? isRename, String? name}) {
          lightCardOverlayCallback(
              isEdit: isEdit, isRename: isRename, name: name);
        },
        closeOverlyCallback: () => closeOverlayView(),
      ),
    );
    Overlay.of(context).insert(_overlayFloat);
  }

  void closeOverlayView() {
    _overlayFloat.remove();
  }
}

class MyDetailOverlay extends StatefulWidget {
  const MyDetailOverlay({
    super.key,
    this.offset,
    this.size,
    required this.deviceLListType,
    required this.lightCardModel,
    required this.lightCardOverlayCallback,
    required this.closeOverlyCallback,
  });

  final Offset? offset;
  final Size? size;
  final HomeDeviceModelDevices lightCardModel;
  final DeviceLListType deviceLListType;

  final LightCardOverlayCallback lightCardOverlayCallback;
  final VoidCallback closeOverlyCallback;

  @override
  State<MyDetailOverlay> createState() => _MyDetailOverlayState();
}

class _MyDetailOverlayState extends State<MyDetailOverlay>
    with SingleTickerProviderStateMixin, WidgetsBindingObserver {
  //输入框控制器，一般用于获取文本、修改文本等
  final TextEditingController _inputController = TextEditingController();
  //焦点节点，一般用于自动获取焦点，取消焦点以便隐藏键盘等
  final FocusNode _inputFocusNode = FocusNode();
  //边框样式
  final OutlineInputBorder _outlineInputBorder = const OutlineInputBorder(
    borderRadius: BorderRadius.all(Radius.circular(7.0)),
    gapPadding: 0,
    borderSide: BorderSide(color: Color.fromRGBO(222, 222, 222, 1), width: 0),
  );

  // 是否显示重命名弹窗
  bool _renameWidgetShow = false;
  // 是否隐藏编辑菜单
  bool _hiddenEditWidget = false;
// 是否隐藏清除文本按钮
  bool _hiddenClearButton = false;

  double _keyboardHeight = (1.sh - 160.w) / 2.0;

  // 动画控制器
  late final AnimationController _menuController = AnimationController(
    duration: const Duration(milliseconds: 150),
    vsync: this,
  );

  @override
  void initState() {
    setState(() {});
    _inputController.text = widget.lightCardModel.name!;
    _hiddenClearButton = widget.lightCardModel.name!.isEmpty;
    _delayAnimation();
    // 初始化
    WidgetsBinding.instance.addObserver(this);
    super.initState();
  }

  // 延迟动画执行
  _delayAnimation() async {
    await Future.delayed(const Duration(milliseconds: 200));
    _menuController.forward();
  }

  @override
  void dispose() {
    _inputController.dispose();
    _menuController.dispose();
    _inputFocusNode.dispose();
    // 销毁
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Animation<double> opacity =
        Tween(begin: 0.0, end: 20.0).animate(_menuController);

    return Positioned.fill(
      child: Material(
        color: Colors.transparent,
        child: ClipRect(
            child: AnimatedBuilder(
                animation: opacity,
                builder: (context, child) {
                  return BackdropFilter(
                    filter: ImageFilter.blur(
                        sigmaX: opacity.value, sigmaY: opacity.value),
                    child: GestureDetector(
                        onTap: () {
                          if (!_renameWidgetShow) {
                            _lightCardOverlayCallback(
                                isEdit: false,
                                isRename: false,
                                name: widget.lightCardModel.name);
                          }
                        },
                        child: Container(
                          width: MediaQuery.of(context).size.width,
                          height: MediaQuery.of(context).size.height,
                          color:
                              Color.fromRGBO(28, 28, 28, 0.038 * opacity.value),
                          child: Stack(
                            children: [
                              Positioned(
                                  left: widget.offset!.dx,
                                  top: widget.offset!.dy,
                                  child: IgnorePointer(
                                    child: SizedBox(
                                      width: widget.size?.width,
                                      height: widget.size?.height,
                                      child: _cardItemWidget,
                                    ),
                                  )).hidden(_renameWidgetShow),
                              _hiddenEditWidget
                                  ? Container()
                                  : _buildEditWidget(),
                              // 重命名
                              _buildRenameWidget()
                            ],
                          ),
                        )),
                  );
                })),
      ),
    );
  }

  // 获取对应类型的设备卡片
  Widget get _cardItemWidget {
    if (widget.deviceLListType == DeviceLListType.light) {
      return LightCardItem(
        widget.lightCardModel,
      );
    }
    return TempCardItem(widget.lightCardModel);
  }

  // 编辑弹窗
  Widget _buildEditWidget() {
    final top = (widget.offset!.dy + widget.size!.height) < 1.sh / 2.0
        ? (widget.offset!.dy + widget.size!.height + 10.r)
        : (widget.offset!.dy - 90.w - 10.r);
    final left = widget.offset!.dx > 1.sw / 2.0
        ? (1.sw - 12.w - 220.w)
        : widget.offset!.dx;
    AlignmentGeometry animationAlignment = Alignment.topLeft;

    if ((widget.offset!.dy + widget.size!.height) < 1.sh / 2.0) {
      if (widget.offset!.dx > 1.sw / 2.0) {
        animationAlignment = Alignment.topRight;
      } else {
        animationAlignment = Alignment.topLeft;
      }
    } else {
      if (widget.offset!.dx > 1.sw / 2.0) {
        animationAlignment = Alignment.bottomRight;
      } else {
        animationAlignment = Alignment.bottomLeft;
      }
    }

    /// 编辑弹窗缩放动画
    Animation<double> scale =
        Tween(begin: 0.0, end: 1.0).animate(_menuController);
    // _bgOpacityController.forward();
    return Positioned(
      top: top,
      left: left,
      child: AnimatedBuilder(
        animation: scale,
        builder: (context, child) {
          return Transform.scale(
            alignment: animationAlignment,
            scale: scale.value,
            child: Container(
              padding: const EdgeInsets.only(left: 10, right: 10),
              width: 220.w,
              height: 90.w,
              clipBehavior: Clip.antiAlias,
              decoration: BoxDecoration(
                color: const Color.fromRGBO(222, 222, 222, 0.15),
                borderRadius: BorderRadius.circular(15),
              ),
              child: Column(
                children: [
                  SizedBox(
                      height: 44.w,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            '重命名',
                            style: 16.ts.copyWith(
                                color: const Color.fromRGBO(238, 238, 238, 1)),
                          ),
                          SvgPicture.asset(
                            SVGImage.listIcRenameSvg,
                            color: const Color.fromRGBO(238, 238, 238, 0.8),
                          )
                        ],
                      ).onClick(() {
                        setState(() {
                          _renameWidgetShow = true;
                          _hiddenEditWidget = true;
                        });
                      })),
                  Container(
                    height: 1,
                    color: const Color.fromRGBO(255, 255, 255, 0.25),
                  ),
                  SizedBox(
                    height: 44.w,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          '编辑视图',
                          style: 16.ts.copyWith(
                              color: const Color.fromRGBO(238, 238, 238, 1)),
                        ),
                        SvgPicture.asset(
                          SVGImage.listIcEditviewSvg,
                          // ignore: deprecated_member_use
                          color: const Color.fromRGBO(238, 238, 238, 0.8),
                        )
                      ],
                    ),
                  ).onClick(() {
                    _lightCardOverlayCallback(
                        isEdit: true,
                        isRename: false,
                        name: widget.lightCardModel.name);
                  })
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  // 重命名弹窗
  Widget _buildRenameWidget() {
    if (_renameWidgetShow) {
      FocusScope.of(context).requestFocus(_inputFocusNode);
    }
    return Positioned(
        bottom: _keyboardHeight + 10,
        left: (1.sw - 280) / 2.0,
        child: AnimatedScale(
            scale: _renameWidgetShow ? 1.0 : 0,
            duration: const Duration(milliseconds: 200),
            child: AnimatedOpacity(
              opacity: _renameWidgetShow ? 1.0 : 0,
              duration: const Duration(milliseconds: 200),
              child: Container(
                padding: const EdgeInsets.fromLTRB(8, 22, 8, 8).r,
                width: 280.w,
                height: 160.w,
                decoration: BoxDecoration(
                    color: const Color.fromRGBO(222, 222, 222, 0.15),
                    borderRadius: BorderRadius.circular(15).r),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text('重命名',
                        style: 16.ts.copyWith(
                            color: const Color.fromRGBO(238, 238, 238, 1))),
                    // 创建输入框
                    _buildTopTextField(context),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Container(
                          alignment: Alignment.center,
                          width: 128.w,
                          height: 40.w,
                          decoration: BoxDecoration(
                              color: const Color.fromRGBO(222, 222, 222, 0.15),
                              borderRadius: BorderRadius.circular(7)),
                          child: Text(
                            '取消',
                            style: 16.ts,
                          ),
                        ).onClick(() {
                          _renameWidgetShow = false;
                          _lightCardOverlayCallback(
                              isEdit: false,
                              isRename: false,
                              name: _inputController.text);
                        }),
                        Container(
                          alignment: Alignment.center,
                          width: 128.w,
                          height: 40.w,
                          decoration: BoxDecoration(
                              color: const Color.fromRGBO(222, 222, 222, 0.15),
                              borderRadius: BorderRadius.circular(7)),
                          child: Text(
                            '确定',
                            style: 16.ts,
                          ),
                        ).onClick(() {
                          _submitLightName();
                        }),
                      ],
                    )
                  ],
                ),
              ),
            )));
  }

  //创建输入框
  Widget _buildTopTextField(BuildContext context) {
    return Container(
        padding: const EdgeInsets.all(8).r,
        height: 40,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: const Color.fromRGBO(222, 222, 222, 0.15),
          borderRadius: BorderRadius.circular(7),
        ),
        clipBehavior: Clip.antiAlias,
        child: Row(
          children: [
            Expanded(
              child: TextField(
                style: 16
                    .ts
                    .copyWith(color: const Color.fromRGBO(238, 238, 238, 1)),
                maxLines: 1,
                controller: _inputController,
                focusNode: _inputFocusNode,
                textInputAction: TextInputAction.done,
                decoration: InputDecoration(
                  hintText: widget.lightCardModel.name,
                  isCollapsed: true, //高度包裹
                  // contentPadding: const EdgeInsets.symmetric(
                  //     horizontal: 8, vertical: 8), //内容内边距，影响高度
                  border: InputBorder.none,
                ),
                textAlign: TextAlign.left,
                onSubmitted: (value) {
                  //提交按钮点击回调
                  _submitLightName();
                },
                onEditingComplete: () {
                  // 输入完成回调
                },
                onChanged: (value) {
                  if (value.isNotEmpty && _hiddenClearButton) {
                    setState(() {
                      _hiddenClearButton = false;
                    });
                  } else if (value.isEmpty) {
                    setState(() {
                      _hiddenClearButton = true;
                    });
                  }
                },
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(left: 8).r,
              child: SvgPicture.asset(
                SVGImage.inputIcCloseSvg,
                width: 22.r,
                height: 22.r,
              ),
            ).onClick(() {
              _inputController.clear();
              setState(() {
                _hiddenClearButton = true;
              });
            }).hidden(_hiddenClearButton),
          ],
        ));
  }

  // 提交修改后的名称
  void _submitLightName() {
    if (_inputController.text.isEmpty) {
    BnwToast.showView(context,infoStr:'请输入灯光名称');
      return;
    }
    _renameWidgetShow = false;
    _inputFocusNode.unfocus();
    _lightCardOverlayCallback(
        isEdit: false, isRename: true, name: _inputController.text);
  }

  // 关闭视图并返回数据
  void _lightCardOverlayCallback(
      {bool? isEdit, bool? isRename, String? name}) async {
    widget.lightCardOverlayCallback(
        isEdit: isEdit, isRename: isRename, name: name);
    _hiddenEditWidget = true;
    _menuController.reverse();
    await Future.delayed(const Duration(milliseconds: 150));
    widget.closeOverlyCallback();
  }

  // 监听键盘弹出
  @override
  void didChangeMetrics() {
    super.didChangeMetrics();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        if (MediaQuery.of(context).viewInsets.bottom == 0) {
          // 关闭键盘
          // print('键盘关闭');
        } else {
          // 显示键盘
          print('键盘弹出');
          // 键盘高度
          final bottom = MediaQuery.of(context).viewInsets.bottom;

          if (bottom >= _keyboardHeight) {
            setState(() {
              _keyboardHeight = bottom;
              // 打印键盘高度
            });
          }
        }
      }
    });
  }
}
